package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Message;
import com.example.forum.model.User;
import com.example.forum.services.IMessageService;
import com.example.forum.services.IUserService;
import com.sun.istack.internal.NotNull;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @ClassName MessageController
 * @Description TODO
 * @Author H.
 * @Date 2023/6/27 16:30
 * @Version 1.0
 */
@Slf4j
@RestController
@Api(tags = "站内信接口")
@RequestMapping("/message")
public class MessageController {
    @Resource
    private IMessageService messageService;
    @Resource
    private IUserService userService;

    @ApiOperation("发送站内信")
    @PostMapping("/send")
    public AppResult send(HttpServletRequest request,
                          @ApiParam("接收用户Id") @RequestParam("receiveUserId") @NotNull Long receiveUserId,
                          @ApiParam("站内信内容") @RequestParam("content") @NonNull String content){
        //从session获取当前用户信息
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //判断是否被禁言
        if(user.getState() != 0){
            log.info(ResultCode.FAILED_USER_BANNED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_BANNED));
        }
        //接受用户id与当前登录用户不能相同(不能自己给自己发站内信)
        if(user.getId() == receiveUserId){
            // 日志
            log.warn("不能给自己发送站内信. postUserId = " + user.getId() + ", receiveUserId = " + receiveUserId);
            // 返回错误信息
            return AppResult.failed(ResultCode.FAILED_CREATE);
        }
        //查询接收用户
        User receiveUser = userService.selectById(receiveUserId);
        if(receiveUser == null || receiveUser.getDeleteState() != 0){
            log.info(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //构造对象
        Message message = new Message();
        message.setPostUserId(user.getId());
        message.setReceiveUserId(receiveUserId);
        message.setContent(content);
        //调用业务层
        messageService.create(message);
        return AppResult.success();
    }

    @ApiOperation("查询用户所有的站内信")
    @GetMapping("/getAll")
    public AppResult<List<Message>> getAllByReceiveUserId(HttpServletRequest request) {
        //获取当前用户登录
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //查询用户站内信
        List<Message> result = messageService.selectByReceiveUserId(user.getId());
        return AppResult.success(result);
    }

    @ApiOperation("读取站内信")
    @GetMapping("/read")
    public AppResult read(HttpServletRequest request,
                          @ApiParam(value = "站内信id") @RequestParam(value = "id") @NonNull Long id){
        //首先获取站内信详情
        Message message = messageService.selectById(id);
        //获取用户信息
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(message == null || user.getId() != message.getReceiveUserId()){
            // 打印日志
            log.warn("查询了不属于自己的站内信：userId = " + user.getId() + ", receiveUserId = " + message.getReceiveUserId());
            // 返回错误结果
            return AppResult.failed(ResultCode.FAILED);
        }
        Message updateMessage = new Message();
        updateMessage.setId(message.getId());
        updateMessage.setState((byte) 1);
        messageService.updateById(updateMessage);
        return AppResult.success();
    }

    @ApiOperation("获取未读消息个数")
    @GetMapping("/getUnreadCount")
    public AppResult<Integer> getUnreadCount(HttpServletRequest request){
        //获取用户信息
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState() != 0){
            // 日志
            log.warn(ResultCode.FAILED_USER_BANNED.toString() + ", userId = " + user.getId());
            // 返回错误信息
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        Integer result = messageService.selectUnreadCount(user.getId());
        return AppResult.success(result);
    }

    @ApiOperation("回复站内信")
    @PostMapping("/reply")
    public AppResult reply(HttpServletRequest request,
                           @ApiParam(value = "当前站内信Id") @RequestParam(value = "repliedId") @NonNull Long repliedId,
                           @ApiParam(value = "接收用户Id") @RequestParam(value = "receiveUserId") @NonNull Long receiveUserId,
                           @ApiParam(value = "站内信内容") @RequestParam(value = "content") @NonNull String content) {
        //获取发送者用户信息
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState() != 0){
            // 日志
            log.warn(ResultCode.FAILED_USER_BANNED.toString() + ", userId = " + user.getId());
            // 返回错误信息
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //不能自己回复自己
        if(user.getId() == receiveUserId){
            // 日志
            log.warn("不能给自己发送站内信. postUserId = " + user.getId() + ", receiveUserId = " + receiveUserId);
            // 返回错误信息
            return AppResult.failed(ResultCode.FAILED_CREATE);
        }
        //查询接收用户
        User receiveUser = userService.selectById(receiveUserId);
        if(receiveUser == null || receiveUser.getDeleteState() != 0){
            // 日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString() + ", receiveUserId = " + receiveUserId);
            // 返回错误信息
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }

        //构造回复对象
        Message message = new Message();
        message.setPostUserId(user.getId());
        message.setReceiveUserId(receiveUserId);
        message.setContent(content);
        //调用业务层代码
        messageService.reply(repliedId,message);

        return AppResult.success();
    }
}
